<template>
  <div class="admin-products">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>商品管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索商品名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="商品状态" clearable>
            <el-option label="全部状态" value="" />
            <el-option label="待审核" value="PENDING" />
            <el-option label="已上架" value="ON_SALE" />
            <el-option label="已下架" value="OFF_SHELF" />
            <el-option label="审核拒绝" value="REJECTED" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.categoryId" placeholder="商品分类" clearable>
            <el-option label="全部分类" value="" />
            <el-option
              v-for="category in categories"
              :key="category.categoryId"
              :label="category.name"
              :value="category.categoryId"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 商品列表 -->
    <div class="table-section">
      <el-table
        :data="productList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="productId" label="ID" width="80" />
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <el-image
              :src="row.mainImage || '/placeholder.png'"
              :preview-src-list="[row.mainImage]"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px;"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            <span class="price">¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sellerId" label="卖家ID" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-dropdown @command="handleCommand" trigger="click">
              <el-button type="primary" size="small">
                操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'edit', row }">
                    <el-icon><Edit /></el-icon>编辑
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="row.status === 'PENDING'"
                    :command="{ action: 'approve', row }"
                  >
                    <el-icon><Check /></el-icon>审核通过
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="row.status === 'PENDING'"
                    :command="{ action: 'reject', row }"
                  >
                    <el-icon><Close /></el-icon>审核拒绝
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="row.status === 'ON_SALE'"
                    :command="{ action: 'offSale', row }"
                  >
                    <el-icon><Remove /></el-icon>下架
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="row.status === 'OFF_SHELF'"
                    :command="{ action: 'onSale', row }"
                  >
                    <el-icon><Plus /></el-icon>上架
                  </el-dropdown-item>
                  <el-dropdown-item 
                    :command="{ action: 'delete', row }"
                    divided
                  >
                    <el-icon><Delete /></el-icon>删除
                  </el-dropdown-item>
                  <el-dropdown-item 
                    :command="{ action: 'toggleBanner', row }"
                    divided
                  >
                    <el-icon><Picture /></el-icon>
                    <span v-if="row.isBanner">取消首页轮播图</span>
                    <span v-else>设为首页轮播图</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑商品对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑商品"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="editForm.price"
            :precision="2"
            :step="0.01"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            v-model="editForm.stock"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="editForm.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="category in categories"
              :key="category.categoryId"
              :label="category.name"
              :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" prop="mainImage">
          <el-input v-model="editForm.mainImage" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="待审核" value="PENDING" />
            <el-option label="已上架" value="ON_SALE" />
            <el-option label="已下架" value="OFF_SHELF" />
            <el-option label="审核拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Edit, Delete, Check, Close, Remove, Plus, ArrowDown, Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const productList = ref([])
const categories = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  categoryId: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 编辑对话框
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const editForm = reactive({
  productId: null,
  name: '',
  price: 0,
  stock: 0,
  categoryId: null,
  mainImage: '',
  description: '',
  status: ''
})

// 编辑表单验证规则
const editRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  status: [{ required: true, message: '请选择商品状态', trigger: 'change' }]
}

// 获取商品列表
const getProductList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await request.get('/api/admin/products', { params })
    productList.value = response.list || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategories = async () => {
  try {
    const response = await request.get('/api/categories')
    categories.value = response || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getProductList()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    categoryId: ''
  })
  pagination.page = 1
  getProductList()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  getProductList()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  getProductList()
}

// 刷新数据
const refreshData = () => {
  getProductList()
}

// 状态相关方法
const getStatusType = (status) => {
  const statusMap = {
    'PENDING': 'warning',
    'ON_SALE': 'success',
    'OFF_SHELF': 'info',
    'REJECTED': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待审核',
    'ON_SALE': '已上架',
    'OFF_SHELF': '已下架',
    'REJECTED': '审核拒绝'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 操作处理
const handleCommand = async ({ action, row }) => {
  try {
    switch (action) {
      case 'edit':
        handleEdit(row)
        break
      case 'approve':
        await handleApprove(row.productId)
        break
      case 'reject':
        await handleReject(row.productId)
        break
      case 'onSale':
        await handleOnSale(row.productId)
        break
      case 'offSale':
        await handleOffSale(row.productId)
        break
      case 'delete':
        await handleDelete(row.productId)
        break
      case 'toggleBanner':
        await handleToggleBanner(row)
        break
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 编辑商品
const handleEdit = (row) => {
  Object.assign(editForm, {
    productId: row.productId,
    name: row.name,
    price: row.price,
    stock: row.stock,
    categoryId: row.categoryId,
    mainImage: row.mainImage,
    description: row.description,
    status: row.status
  })
  editDialogVisible.value = true
}

// 提交编辑
const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    await request.put(`/api/admin/products/${editForm.productId}`, editForm)
    ElMessage.success('编辑成功')
    editDialogVisible.value = false
    getProductList()
  } catch (error) {
    console.error('编辑失败:', error)
    ElMessage.error('编辑失败')
  } finally {
    editLoading.value = false
  }
}

// 审核通过
const handleApprove = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要审核通过这个商品吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.post(`/api/admin/products/${productId}/approve`)
    ElMessage.success('审核通过成功')
    getProductList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

// 审核拒绝
const handleReject = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要拒绝这个商品吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.post(`/api/admin/products/${productId}/reject`)
    ElMessage.success('审核拒绝成功')
    getProductList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

// 上架
const handleOnSale = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要上架这个商品吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.post(`/api/admin/products/${productId}/on-sale`)
    ElMessage.success('上架成功')
    getProductList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('上架失败:', error)
      ElMessage.error('上架失败')
    }
  }
}

// 下架
const handleOffSale = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要下架这个商品吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.post(`/api/admin/products/${productId}/off-sale`)
    ElMessage.success('下架成功')
    getProductList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('下架失败:', error)
      ElMessage.error('下架失败')
    }
  }
}

// 删除商品
const handleDelete = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？此操作不可恢复！', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`/api/admin/products/${productId}`)
    ElMessage.success('删除成功')
    getProductList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 轮播图操作
const handleToggleBanner = async (row) => {
  if (!row.isBanner) {
    // 设为轮播图前先统计当前已设数量
    const count = productList.value.filter(p => p.isBanner).length
    if (count >= 3) {
      ElMessage.warning('最多只能设置3个首页轮播图商品')
      return
    }
  }
  try {
    await request.post(`/api/admin/products/${row.productId}/banner`, null, { params: { isBanner: !row.isBanner } })
    ElMessage.success(!row.isBanner ? '已设为首页轮播图' : '已取消首页轮播图')
    getProductList()
  } catch (error) {
    if (error?.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
  }
}

// 页面初始化
onMounted(() => {
  getProductList()
  getCategories()
})
</script>

<style scoped>
.admin-products {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-section {
  padding: 20px;
  display: flex;
  justify-content: center;
  background: white;
}

.price {
  color: #e6a23c;
  font-weight: 600;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 